/**
 * @projectName demo-master
 * @fileName FeignUtil.java
 * @packageName org.example.customer.util
 * @author xaoyaoyao
 * @date 2021/3/30 10:12
 * @version V1.0
 * @copyright (c) 2021, xaoyaoyao@aliyun.com All Rights Reserved.
 */
package org.example.customer.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import feign.Feign;
import feign.Logger;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.okhttp.OkHttpClient;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.example.customer.annotation.SelfFeignClient;
import org.example.customer.feign.CustomerClient;
import org.example.customer.feign.HelloWorld;

/**
 * @author xaoyaoyao
 * @className FeignUtil
 * @description
 * @date 2021/3/30 10:12
 */
public class FeignUtil<T> {

	private String url(Class<T> clazz) {
		SelfFeignClient selfFeignClient = clazz.getAnnotation(SelfFeignClient.class);
		if (null == selfFeignClient) {
			throw new RuntimeException("该类没有指定注解<SelfFeignClient>");
		}
		return selfFeignClient.url();
	}

	public T send(Class<T> clazz) {
		String baseUrl = url(clazz);
		if (null == baseUrl || StringUtils.isBlank(baseUrl)) {
			throw new RuntimeException("调用的服务Url 为空");
		}
		return Feign.builder()
				.logger(new Logger.JavaLogger(clazz).appendToFile("logs/http.log"))
				.logLevel(Logger.Level.FULL)
				.client(new OkHttpClient())
				.encoder(new JacksonEncoder())
				.decoder(new JacksonDecoder())
				.target(clazz, baseUrl);
	}

	public static Map<String, Object> toMap(Object object) {
		JSONObject                     jsonObject = (JSONObject) JSON.toJSON(object);
		Set<Map.Entry<String, Object>> entrySet   = jsonObject.entrySet();
		Map<String, Object>            map        = new HashMap<String, Object>();
		for (Map.Entry<String, Object> entry : entrySet) {
			map.put(entry.getKey(), entry.getValue());
		}
		return map;
	}

	public static void main(String[] args) {
		CustomerClient send = new FeignUtil<CustomerClient>()
				.send(CustomerClient.class);
		HelloWorld helloWorld = new HelloWorld();
		helloWorld.setParam("test1");
		HelloWorld helloWorld1 = send.testFeignApiHasParameterBJson(helloWorld);
		System.out.println(helloWorld1);
	}
}
